<?php
declare(strict_types=1);
namespace Service\ActivityService;

use App\Model\BbcModel\ActivityDiscount;
use App\Model\BbcModel\ActivityDrop;
use App\Model\BbcModel\ActivitySend;
use App\Model\BbcModel\Goods;
use App\Model\BbcModel\GoodsBatch;
use App\Model\BbcModel\Member;
use App\Model\BbcModel\MnStoreGoods;
use Service\BaseService;
use App\Model\BbcModel\MnActivityGoods;
use App\Model\BbcModel\StoreActivity;
use App\Model\BbcModel\ActivityStore;
use App\Model\BbcModel\Vip;
use Hyperf\DbConnection\Db;
use App\Model\BbcModel\Mnuser;
use Service\Code\Normal;
use Service\ConfigureService\ChannelConfigService;
use Service\GoodsService\ChannelGoodsService;
use Service\GoodsService\GoodsBatchService;
use Service\GoodsService\GoodsSpecPriceService;
use Service\GoodsService\DistributorSpecPriceService;
use App\Model\BbcModel\ActivityBook;
use App\Model\BbcModel\ActivityPush;
use App\Model\BbcModel\Goodsbrand;
use App\Model\BbcModel\MnActivity;
use Service\GoodsService\MnGoodsService;
use App\Model\BbcModel\Activity;
use App\Model\BbcModel\ActivityGoods;
use App\Model\BbcModel\BookTeam;
use App\Model\BbcModel\ActivitySeckill;
use App\Model\BbcModel\Order;
use App\Model\BbcModel\MemberInfo;

/**
 * 店铺活动服务中心
 * @author chenshubo
 */
class ActivityStoreService extends BaseService
{
    /**
     * 获取活动商品数据
     * @param array $actIds
     */
    public function getActivityGoodsList( array $actIds = [] )
    {
        if( empty($actIds) ) {
            return [];
        }
        
        return MnActivityGoods::instance()
        ->whereIn('mn_activity_id',$actIds)
        ->where('df',0)
        ->get()
        ->toArray();
    }

    /**
     * 获取店铺拼团和秒杀活动最近一场活动及活动商品
     * @param int $cid
     * @param int $mn_sid
     * @param int $mid
     * @return array|null[]
     */
    public function getStoreSpecialActivity(int $cid = 0,int $mn_sid = 0,int $mid = 0,$config_channel = []){
        if(empty($cid) || empty($mn_sid)){
            return ['bookActivity'=>[],'seckillActivity'=>[]];
        }
        $date = strtotime(date('Y-m-d',time()));
        $time = time();
        $where = "cid={$cid} and (mn_sid=0 or mn_sid={$mn_sid}) and enddate>{$date}";

        $vip_type = 0;
        if(!empty($config_channel) && isset($config_channel['vip_type']) && $config_channel['vip_type'] == 1){
            $vip_type = json_decode($config_channel['value'],true);
            if($vip_type['vip_type'] == 1){ //非会员模式
                $vip_type = 1;
                $where .= ' and target_type <> 3';
            }
        }
        //查询店铺禁用的活动
        $banList = StoreActivity::instance()->where(['mn_sid'=>$mn_sid])->get()->toArray();
        if(!empty($banList)){
            $banIds = implode(',',array_column($banList,'activity_id'));
            $where .= " and activity_id not in ($banIds)";
        }
        $activityList = ActivityStore::instance()->where([
            ['cid','=',$cid],
            ['enddate','>',$date],
            [function($query) use ($mn_sid){
                $query->where('mn_sid','=',0)->orwhere('mn_sid','=',$mn_sid);
            }],
            [function($query) use ($vip_type){
                if($vip_type == 1){
                    $query->where(['target_type','<>',3]);
                }
            }],
            [function($query) use ($banList){
                if(!empty($banList)){//非会员模式
                    $banIds = array_column($banList,'activity_id');
                    $query->whereNotIn('activity_id',$banIds);
                }
            }]
        ])->pluck('activity_id')->toArray();
        if(empty($activityList)){
            return ['bookActivity'=>[],'seckillActivity'=>[]];
        }
        //已经开始
        $map1 =[
            ['cid','=',$cid],
            ['df','=',0],
            ['status','<>',2],
            [function($query) use($activityList){
                $query->whereIn('sync_online',[0,2])
                    ->whereIn('id',$activityList);
            }],
        ];
        //未开始但开启预约
        $map2 = [
            ['cid','=',$cid],
            ['df','=',0],
            ['status','<>',2],
            ['pre_notice','=',1],
            ['begindate','<=',$date+48*60*60],
            [function($query) use($activityList){
                $query->whereIn('sync_online',[0,2])
                    ->whereIn('id',$activityList);
            }],
        ];
        if($mid){
            $isVip = Vip::instance()->check(['mid'=>$mid,'mn_sid'=>$mn_sid]);
            if($isVip['is_vip']==1){
                $map1[] = [
                    function($query){
                        $query->whereIn('target_type',[1,3,4]);
                    }
                ];
                $map2[] = [
                    function($query){
                        $query->whereIn('target_type',[1,3,4]);
                    }
                ];
            }else{
                $map1[] = [
                    function($query){
                        $query->whereIn('target_type',[1,2,4]);
                    }
                ];
                $map2[] = [
                    function($query){
                        $query->whereIn('target_type',[1,2,4]);
                    }
                ];

            }
        }else{
            $map1[] = [
                function($query){
                    $query->whereIn('target_type',[1,2,4]);
                }
            ];
            $map2[] = [
                function($query){
                    $query->whereIn('target_type',[1,2,4]);
                }
            ];
        }
        $order = 'begindate desc,id desc';

        /**
         * 拼团活动
         */
        $map_1 = array_merge($map1,[['type','=',4]]);
        $map_2 = array_merge($map2,[['type','=',4]]);
        $bookActivityList = Db::table('ly_activity')
            ->Where($map_1)
            ->orWhere($map_2)
            ->orderByRaw($order)
            ->get()->toArray();
        $bookActivity = [];
        foreach ($bookActivityList as $k=>$v){
            $bookActivity   = $v;
            $time_start_str = strtotime($bookActivity['begintime']);
            $time_end_str   = strtotime($bookActivity['endtime']);
            if( $time > $bookActivity['begindate'] && $time>$time_end_str && date('Y-m-d',$time)==date('Y-m-d',$bookActivity['enddate'])){
                $bookActivity = $bookActivityList[$k] ?? null;
                if($bookActivity &&  $bookActivity['pre_notice']==1 && $bookActivity['begindate']-$time<172800){
                    $bookActivity = $this->checkActivityTime(['activity'=>$bookActivity,'time'=>$time,'time_start_str'=>$time_start_str,'time_end_str'=>$time_end_str]);
                }else{
                    $bookActivity = null;
                }
            }else{
                $bookActivity = $this->checkActivityTime(['activity'=>$bookActivity,'time'=>$time,'time_start_str'=>$time_start_str,'time_end_str'=>$time_end_str]);
            }
            if($bookActivity['begindate'] <= $date){ //已开始
                $end_time = strtotime(date('Y-m-d',$bookActivity['enddate']).' '.$bookActivity['endtime']);//当前也结束
                if($end_time < $time){
                    $bookActivity = null;
                }
            }
            if($bookActivity == null){
                continue;
            }
            $bookActivity['goods'] = [];
            $bookActivityGoods = $this->activityGoodsList($cid,$mn_sid,$mid,[$bookActivity],0,7,['type'=>4]);
            if(count($bookActivityGoods) > 0){
                $bookActivity['goods'] = $bookActivityGoods;
                break;
            }
        }
        /**
         * 秒杀活动
         */
        $map_3 = array_merge($map1,[['type','=',3]]);
        $map_4 = array_merge($map2,[['type','=',3]]);
        $seckillActivityList = Db::table('ly_activity')
            ->Where($map_3)
            ->orWhere($map_4)
            ->orderByRaw($order)
            ->get()->toArray();
        $seckillActivity = [];
        foreach ($seckillActivityList as $k=>$v){
            $seckillActivity = $v;
            $time_start_str = strtotime($seckillActivity['begintime']);
            $time_end_str = strtotime($seckillActivity['endtime']);
            if($date>$seckillActivity['begindate'] && $date>$time_end_str && date('Y-m-d',$date)==date('Y-m-d',$seckillActivity['enddate'])){
                $seckillActivity = $seckillActivityList[$k] ?? null;
                if($seckillActivity && $seckillActivity['pre_notice']==1 && $seckillActivity['begindate']-$time<172800){
                    $seckillActivity = $this->checkActivityTime(['activity'=>$seckillActivity,'time'=>$time,'time_start_str'=>$time_start_str,'time_end_str'=>$time_end_str]);
                }else{
                    $seckillActivity = null;
                }
            }else{
                $seckillActivity = $this->checkActivityTime(['activity'=>$seckillActivity,'time'=>$time,'time_start_str'=>$time_start_str,'time_end_str'=>$time_end_str]);
            }
            if($seckillActivity['begindate'] <= $date){ //已开始
                $end_time = strtotime(date('Y-m-d',$seckillActivity['enddate']).' '.$seckillActivity['endtime']);//当前也结束
                if($end_time<$time){
                    $seckillActivity = null;
                }
            }
            if($seckillActivity == null){
                continue;
            }
            $seckillActivity['goods'] = [];
            $seckillActivityGoods = $this->activityGoodsList($cid,$mn_sid,$mid,[$seckillActivity],0,7,['type'=>4]);
            if(count($seckillActivityGoods) > 0){
                $seckillActivity['goods'] = $seckillActivityGoods;
                break;
            }

        }
        return [
            'bookActivity'=>$bookActivity,
            'seckillActivity'=>$seckillActivity,
        ];
    }

    /**
     * 检查活动时间
     * @param array $param
     * @return string
     */
    public function checkActivityTime( array $param)
    {
        $activity       = $param['activity'];
        $time           = $param['time'];
        $time_start_str = $param['time_start_str'];
        $time_end_str   = $param['time_end_str'];
        if($time<$activity['begindate']/* && $activity['begindate']-$time<172800*/){
            $activity['start']     = 0;
//            $activity['countdown'] = $activity['begindate'] - $time;
            $activity['countdown'] = strtotime(date('Y-m-d',$activity['begindate']).$activity['begintime'])-$time;
            $activity['show_time'] = date('m月d日', $activity['begindate']) . ' ' . date('H:i', strtotime($activity['begintime']));
        }
        if($time>$activity['begindate'] && $time<$time_start_str){
            $activity['start']     = 0;
            $activity['countdown'] = $time_start_str - $time;
            $activity['show_time'] = date('H:i', strtotime($activity['begintime']));
        }
        if($time>$activity['begindate'] && $time>$time_end_str){
            $activity['start']     = 0;
            $activity['countdown'] = $time_start_str + 86400 - $time;
            $activity['show_time'] = date('m月d日', $activity['begindate']) . ' ' . date('H:i', strtotime($activity['begintime']));
        }
        if($time>$activity['begindate'] && $time<=$time_end_str && $time>=$time_start_str){
            $activity['start']     = 1;
            $activity['countdown'] = $time_end_str - $time;
            $activity['show_time'] = '';
        }
        return $activity;
    }

    /**
     * 店铺活动商品列表
     * @param int $cid
     * @param int $mn_sid
     * @param int $mid
     * @param array $channelActivityList
     * @param int $page
     * @param int $limit
     * @param int $param [type:3-秒杀 4-拼团]
     * @return array
     */
    public function activityGoodsList(int $cid,int $mn_sid,int $mid,array $storeActivityList,int $page = 0,int $limit = 20, array $param)
    {
        $mn_user = Mnuser::instance()->where(['id'=>$mn_sid])->first();
        $map = array_column($storeActivityList,null,'id');
        $act_ids = array_keys($map);
        $list = Db::table('ly_activity_goods')
            ->leftJoin('ly_mn_store_goods','ly_activity_goods.goods_id', '=', 'ly_mn_store_goods.goods_id')
            ->leftJoin('ly_goods','ly_goods.id','=','ly_mn_store_goods.goods_id')
            ->where([['ly_mn_store_goods.mn_sid','=',$mn_sid],['ly_mn_store_goods.status','=',1]])
            ->whereIn('ly_activity_goods.activity_id',$act_ids)
            ->where('ly_activity_goods.buy_limit_num','>',0)
            ->where(function ($query) use ($mn_user,$cid){
                if($mn_user['type'] == 2){
                    $query->select(DB::raw("((ly_goods.status=1 and ly_goods.df=0 and ly_goods.is_trade=0) or (ly_goods.is_trade=1 and (ly_mn_store_goods.df=0 or (ly_mn_store_goods.df=1 and ly_mn_store_goods.num>0) or (ly_mn_store_goods.pre_sell=1 and ly_mn_store_goods.pre_storage>0))))"));
                }else{
                    $query->select(DB::raw("ly_goods.is_trade=0 and ly_goods.status=1 and ly_goods.df=0 and ly_goods.cid=$cid"));
                }
            })
            ->where(function ($query) use ($mn_user){
                if($mn_user['type']==3){
                    switch ($mn_user['goods_source']){
                        case 1://只卖普通仓
                            $query->where('ly_goods.is_fast_delivery','=',0);
                            break;
                        case 2://只卖前置仓
                            $query->where('ly_goods.supplier_id','=',$mn_user['supplier_id']);
                            break;
                        case 3://前置仓+普通仓
                            $query->where(function ($query) use($mn_user){
                                $query->where('ly_goods.supplier_id','=',$mn_user['supplier_id'])
                                    ->orwhere('ly_goods.is_fast_delivery','=',0);
                            });
                            break;
                        case 4://只卖中心仓
                            $query->where('ly_goods.is_fast_delivery','<>',2);
                            break;
                        case 5://中心仓+普通仓
                            $query->where('ly_goods.is_fast_delivery','<>',1);
                            break;
                        case 6://中心仓+前置仓
                            $query->where(function ($query) use($mn_user){
                                $query->where('ly_goods.supplier_id','=',$mn_user['supplier_id'])
                                    ->orwhere('ly_goods.is_fast_delivery','=',2);
                            });
                            break;
                        case 7://所有仓
                            $query->where(function ($query) use($mn_user){
                                $query->where('ly_goods.supplier_id','=',$mn_user['supplier_id'])
                                    ->whereIn('ly_goods.is_fast_delivery',[0,2]);
                            });
                            break;
                    }
                }else{
                    $query->where('ly_goods.is_fast_delivery','<>',1);
                }
            })
            ->select(['ly_activity_goods.goods_id','ly_activity_goods.price','ly_activity_goods.price_second','ly_activity_goods.price_third','ly_activity_goods.price_forth','ly_activity_goods.buy_limit_num','ly_activity_goods.activity_id','ly_goods.brand_id'])
            ->orderBy('ly_activity_goods.id', 'desc')
            ->offset($page)
            ->limit($limit)
            ->get()->toArray();
        //用户等级确认
        $return = [];
        $user_level  = 0;
        if( $mid ) {
            $store = Mnuser::instance()->where(['mid'=>$mid,'pid'=>$cid,'new_store'=>1])->first();
            if( $store ) {
                $user_level = $store['level'];
            }
        }

        //小B自采订单配置
        $price_type = 0;
        $permit     = ChannelConfigService::instance()->getChannelConfig('btb_buy', $cid);
        if( isset($permit['price_type']) && $permit['price_type'] == 1 ) {
            $price_type = 1;
        }

        //价格小数设置
        $settingConfig = ChannelConfigService::instance()->getChannelConfig('price_decimal', $cid);
        $settingPrice  = $settingConfig['price'] ?? 0;


        $goodsList = [];
        //查询活动商品基础数据
        $goodsIds = array_column($list,'goods_id');
        $storeGoodsList = ChannelGoodsService::instance()->queryGoodsList($goodsIds);
        $storeGoodsListMap = array_column($storeGoodsList,null,'id');

        //查询商品批次信息
        $storeGoodsBatchList = GoodsBatchService::instance()->getChannelGoodsBatchList($cid,$goodsIds);
        $storeGoodsBatchListMap = GoodsBatchService::instance()->getMapList($storeGoodsBatchList);

        //查询商品规格价格信息
        $storeGoodsSpecPriceList = GoodsSpecPriceService::instance()->getGoodsSpecPriceList($goodsIds);
        $storeGoodsSpecPriceListMap = GoodsSpecPriceService::instance()->getMapList($storeGoodsSpecPriceList);

        //分销商等级结算价
        $distributorPriceList = DistributorSpecPriceService::instance()->getGoodsDistributorPriceList($goodsIds);
        $distributorPriceListMap = DistributorSpecPriceService::instance()->getMapList($distributorPriceList);

        //拼团配置获取
        $storeBookingList = $this->getBookingList($act_ids);
        $storeBookingListMap = getArrayGroupData($storeBookingList,'activity_id');

        //获取活动微信推送模板
        $pushTemplate = ActivityPush::instance()->whereIn('activity_id',$act_ids)->select(['activity_id','template_id'])->get()->toArray();
        $pushTemplateListMap = getArrayGroupData($pushTemplate,'activity_id');


        $brand_list = Goodsbrand::instance()
            ->where(['cid'=>$cid,'df'=>0])
            ->select(['id','name'])
            ->get()->toArray();
        $brand_list_map = array_column($brand_list,null,'id');

        foreach ($list as $goods )
        {
            $goods_id       = $goods['goods_id'];
            $activity_id    = $goods['activity_id'];
            $activity_info  = $map[$activity_id];
            $goods['type']                  = $activity_info['type'];
            $goods['price_type']            = $price_type;
            $goods['level']                 = $user_level;
            $goods['settingPrice']          = $settingPrice;
            $result = [];
            if( isset($storeGoodsListMap[$goods_id]) )
            {
                $goods['baseGoods']             = $storeGoodsListMap[$goods_id];
                $goods['baseGoods']['activity_id'] = $activity_id;
                $goods['baseGoodsBatch']        = $storeGoodsBatchListMap[$goods_id] ?? [];
                $goods['baseGoodsSpecPrice']    = $storeGoodsSpecPriceListMap[$goods_id] ?? [];
                $goods['baseGoodsDistributorPrice'] = $distributorPriceListMap[$goods_id] ?? [];
                $goods['channelBooking'] = $storeBookingListMap[$activity_id] ?? [];
                $goods['brand_name'] = $brand_list_map[$goods['brand_id']]['name'] ?? '';
                $result = ActivityGoodsService::instance()->checkGoodsPriceList($cid,$mn_sid,$mid,$goods,$param,$pushTemplateListMap);
                //活动商品库存
                if( $activity_info['type'] == 3 || $activity_info['type'] == 4 ) {
                    $result['num_storage'] = $goods['buy_limit_num'];
                }
                $return[] = $result;
            }
        }
        return $return;
    }

    /**
     * 获取活动数据
     * @param array $actIds
     */
    public function getBookingList( array $actIds = [] )
    {
        if( empty($actIds) ) {
            return [];
        }

        return ActivityBook::instance()
            ->whereIn('activity_id',$actIds)
            ->get()
            ->toArray();
    }

    /**
     * 获取店铺拼团有效数据
     * @param int $cid
     * @param int $mn_sid
     * @param int $activityID
     * @return mixed
     */
    public function getMnActivityOne(int $cid,int $mn_sid,int $activityID)
    {
        if( ! $activityID ) {
            return [];
        }

        if(StoreActivity::instance()->info(['mn_sid'=>$mn_sid,'activity_id'=>$activityID])){ //店铺禁用了此活动
            return [];
        }

        $info = ActivityStore::instance()->where(function($query) use ($mn_sid,$activityID)
        {
            $query->whereOr(function($query) use ($mn_sid,$activityID)
            {
                $query->where('mn_sid',$mn_sid)->where('activity_id',$activityID);
            })
                ->whereOr(function($query) use ($mn_sid,$activityID)
                {
                    $query->where('mn_sid',0)->where('activity_id',$activityID);
                });
        })
            ->first();

        return $info->toArray() ?? [];
    }

    /**
     * 特价活动数据
     * @param int $cid
     * @param int $mn_sid
     * @param array $mn_user
     * @return mixed
     */
    public function getMnSpecialActivityGoodsList(int $cid,int $mn_sid,array $mn_user)
    {
        //特价活动数据获取
        $special_activity = MnActivity::instance()
            ->where(function( $query ) use ($mn_sid)
            {
                $query->where(function( $query ) use ($mn_sid)
                {
                    $time = time();
                    $query->where('df',0)
                        ->where('status',1)
                        ->where('mn_sid',$mn_sid)
                        ->where('startdate', '<=', $time + 48 * 60 * 60)
                        ->where('enddate', '>', $time);

                })
                    ->orWhere(function( $query ) use ($mn_sid)
                    {
                        $time = time();
                        $query->where('df',0)
                            ->where('status',1)
                            ->where('mn_sid',$mn_sid)
                            ->where('startdate','>=', $time)
                            ->where('enddate','>=', $time);

                    });
            })
            ->orderByRaw('startdate asc,md asc')
            ->limit(1)
            ->first();
        if( empty($special_activity) ) {
            return [];
        }

        $special_activity_id    = $special_activity['id'];

        $mn_special_goods_list = MnActivityGoods::instance()
            ->leftJoin('ly_goods', 'ly_goods.id','=','ly_mn_activity_goods.goods_id')
            ->rightJoin('ly_mn_store_goods', 'ly_goods.id','=','ly_mn_store_goods.goods_id')
            ->where('ly_mn_activity_goods.mn_activity_id',$special_activity_id)
            ->where('ly_mn_store_goods.mn_sid',$mn_sid)
            ->where('ly_mn_store_goods.status',1)
            ->where('ly_mn_activity_goods.df',0)
            ->where(function ($query) use ($mn_user,$cid){
                if($mn_user['type'] == 2){
                    $query->selectRaw(Db::raw("((ly_goods.status=1 and ly_goods.df=0 and ly_goods.is_trade=0) or (ly_goods.is_trade=1 and (ly_mn_store_goods.df=0 or (ly_mn_store_goods.df=1 and ly_mn_store_goods.num>0) or (ly_mn_store_goods.pre_sell=1 and ly_mn_store_goods.pre_storage>0))))"));
                }else{
                    $query->selectRaw(Db::raw("ly_goods.is_trade=0 and ly_goods.status=1 and ly_goods.df=0 and ly_goods.cid=$cid"));
                }
            })
            ->where(function ($query) use ($mn_user){
                if($mn_user['type']==3){
                    switch ($mn_user['goods_source']){
                        case 1://只卖普通仓
                            $query->selectRaw(Db::raw("(ly_goods.is_fast_delivery=0)"));
                            break;
                        case 2://只卖前置仓
                            $query->selectRaw(Db::raw("(ly_goods.supplier_id=$mn_user[supplier_id])"));
                            break;
                        case 3://前置仓+普通仓
                            $query->selectRaw(Db::raw("((ly_goods.supplier_id=$mn_user[supplier_id]) or (ly_goods.is_fast_delivery=0))"));
                            break;
                        case 4://只卖中心仓
                            $query->selectRaw(Db::raw("(ly_goods.is_fast_delivery=2)"));
                            break;
                        case 5://中心仓+普通仓
                            $query->selectRaw(Db::raw("(ly_goods.is_fast_delivery<>1)"));
                            break;
                        case 6://中心仓+前置仓
                            $query->selectRaw(Db::raw("((ly_goods.supplier_id=$mn_user[supplier_id]) or (ly_goods.is_fast_delivery=2))"));
                            break;
                        case 7://所有仓
                            $query->selectRaw(Db::raw("((ly_goods.supplier_id=$mn_user[supplier_id]) or (ly_goods.is_fast_delivery in (0,2)))"));
                            break;
                    }
                }else{
                    $query->selectRaw(Db::raw("(ly_goods.is_fast_delivery <> 1)"));
                }
            })
            ->select(explode(',','ly_goods.id,ly_goods.name,ly_goods.img,ly_goods.price_market,ly_goods.price_vip,ly_goods.price_cost,ly_goods.skucode,ly_goods.barcode,ly_goods.num_storage,ly_goods.price_recommend,ly_goods.price_recommend_vip,ly_goods.is_bonded,ly_goods.tax_free,ly_goods.tax_rate,ly_mn_activity_goods.price as mag_price'))
            ->limit(7)
            ->get()->toArray();
        if( empty($mn_special_goods_list) ) {
            return [];
        }

        //计算商品收益率
        //店铺等级
        $mn_user_level          = $mn_user['level'];
        $goods_ids              = array_column($mn_special_goods_list,'id');
        $profitGoodsPriceLists  = MnGoodsService::instance()->getGoodsAllProfit($mn_sid,$goods_ids,1,$mn_user_level);
        $profitGoodsPriceListMap = array_column($profitGoodsPriceLists,null,'goods_id');

        //价格小数设置
        $settingConfig = ChannelConfigService::instance()->getChannelConfig('price_decimal', $cid);
        $settingPrice  = $settingConfig['price'] ?? 0;
        foreach ($mn_special_goods_list as & $goods)
        {
            $profit = $profitGoodsPriceListMap[$goods['id']];
            $goods['price_store']   = $profit['price_store'] ?? 0.00;
//            $goods['price_store']   = $goods['price_store'];
            $goods['price_goods']   = bcadd((string)$goods['price_store'], (string)$profit['profit'], 2);
            $goods['price_vip']     = bcadd((string)$goods['price_store'], (string)$profit['profit_vip'], 2);
            $goods['special_price'] = $goods['mag_price'];
            $goods['price_market']  = $profit['price_market'];

            if( $settingPrice == 0 ) {
                if($goods['is_bonded']==1 && $goods['tax_free']==0){//计算税费
                    $goods['price_recommend']     = upDecimal($goods['price_recommend'] + $goods['price_recommend'] * $goods['tax_rate'], 1);
                }else{
                    $goods['price_recommend']     = upDecimal($goods['price_recommend'],1);
                }
                $goods['price_goods']   = upDecimal($goods['price_goods'],1);
                $goods['price_vip']     = upDecimal($goods['price_vip'],1);
                $goods['special_price'] = upDecimal($goods['mag_price'],1);
                $goods['price_market']  = upDecimal($profit['price_market'],1);
            }else{
                if($goods['is_bonded']==1 && $goods['tax_free']==0){//计算税费
                    $goods['price_recommend']     = ceil($goods['price_recommend'] + $goods['price_recommend'] * $goods['tax_rate']);
                }else{
                    $goods['price_recommend']     = ceil($goods['price_recommend']);
                }
                $goods['price_goods']   = ceil((float)$goods['price_goods']);
                $goods['price_vip']     = ceil((float)$goods['price_vip']);
                $goods['special_price'] = ceil($goods['mag_price']);
                $goods['price_market']  = ceil($profit['price_market']);
            }
        }

        return [
            'special_activity'          => $special_activity,
            'special_activity_goods'    => $mn_special_goods_list
        ];
    }

    /**
     * 获取店铺商品促销
     * @param int $cid
     * @param int $mn_sid
     * @param int $mid
     * @param array $mn_user
     * @param array $goods_ids
     * @param array $is_vip
     */
    public function getStoreActivity(int $cid,int $mn_sid,int $mid,array $mn_user,array $goods_ids,array $is_vip)
    {
        $time = time();

        //查询店铺的活动
        $activityList = Db::table('ly_activity_store')
            ->select(['ly_activity_store.activity_id'])
            ->join('ly_activity','ly_activity.id','=','ly_activity_store.activity_id')
            ->whereIn('ly_activity.status',[0,1])
            ->whereNotExists(function($query) use ($mn_sid)
            {
                $query
                    ->from('ly_store_activity')
                    ->whereRaw("ly_store_activity.activity_id=ly_activity_store.activity_id")
                    ->where('ly_store_activity.mn_sid',$mn_sid);
            })
            ->where('ly_activity_store.cid',$cid)
            ->where(function($query) use ($mn_sid)
            {
                $query->orWhere('ly_activity_store.mn_sid',0)
                    ->orWhere('ly_activity_store.mn_sid',$mn_sid);
            })
            ->where('ly_activity_store.enddate','>',$time)
            ->get()->toArray();
        $default_activity = [
            'fullActivity'      => null,
            'fullActivityInfo'  => null,
            'goodsActivity'     => null,
            'bookActivity'      => null,
            'seckillActivity'   => null,
            'detailTag'         => null,
            'listTag'           => null,
            'fullTag'           => '',
            'sendActivity'      => 0,
        ];

        if( empty($activityList) ) {
            return [
                $default_activity
            ];
        }
        //获取所有活动ID
        $activity_ids = array_column($activityList,'activity_id');
        //获取所有满足条件的活动清单
        $time_now = date('H:i:s',time());

        //店铺类型
        $store_user_type = $mn_user['type'];
        $query = Activity::instance()
            ->select([
                'id',
                'name',
                'begindate',
                'enddate',
                'begintime',
                'endtime',
                'rule_type',
                'act_super'
            ])
            ->whereIn('id',$activity_ids)
            ->where('cid',$cid)
            ->where('df',0)
            ->where('status',1)
            ->where('begintime','<=',$time_now)
            ->where('endtime','>=',$time_now)
            ->whereIn('sync_online',[0,2]);

        //默认1 线上分销2:o2o，3-前置仓店
        if( $store_user_type == 1 ) {
            $query->where('rule_type','<>',1);
        }

        //会员
        if( $is_vip['is_vip']  == 1 ) {
            $query->whereIn('target_type',[1,3,4]);
        } else {
            if($mid==0){
                $query->where('target_type',1);
            }else{
                $query->whereIn('target_type',[1,2,4]);
            }
        }

        $find = $query->where('type',1)->orderByRaw('id desc')->first();
        if( empty($find) ) {
            $fullActivity =$fullActivityInfo =null;
        }else{
            $fullActivity =$fullActivityInfo   = $find->toArray();
            $new_activity_list = [$fullActivity];
            $act_gp_data    = getArrayGroupData($new_activity_list,'rule_type');

            //如果存在买赠
            $act_send = [];
            if( isset($act_gp_data[ActivityService::act_rule_type_send]) ) {
                $ids = array_column($act_gp_data[ActivityService::act_rule_type_send],'id');
                $act_send_list = ActivitySendService::instance()->getActDataList($ids);
                $act_send_list_group = getArrayGroupData($act_send_list,'activity_id');
            }

            //如果存在直降
            if( isset($act_gp_data[ActivityService::act_rule_type_drop]) ) {
                $ids = array_column($act_gp_data[ActivityService::act_rule_type_drop],'id');
                $act_drop_list = ActivityDropService::instance()->getActDataList($ids);
                $act_drop_list_group = getArrayGroupData($act_drop_list,'activity_id');
            }

            //如果存在打折
            if( isset($act_gp_data[ActivityService::act_rule_type_discount]) ) {
                $ids = array_column($act_gp_data[ActivityService::act_rule_type_discount],'id');
                $act_discount_list = ActivityDiscountService::instance()->getActDataList($ids);
                $act_discount_list_group = getArrayGroupData($act_discount_list,'activity_id');
            }

        }


        //查询商品明细
        $baseGoodsList = ChannelGoodsService::instance()->queryGoodsList($goods_ids);

        //获取活动商品
        $activityGoodsList  = ActivityGoods::instance()->select(explode(',','activity_id,goods_id'))->distinct()->whereIn('goods_id',$goods_ids)->get()->toArray();
        $goods_act_ids      = array_column($activityGoodsList,'activity_id');
        $goods_act_ids      = array_unique($goods_act_ids);
        $intersect_act_ids  = array_intersect($activity_ids,$goods_act_ids);
        //针对所有活动进行分组
        $activityGoodsGroup  = getArrayGroupData($activityGoodsList,'goods_id');
        //如果和店铺的活动有交集
        $has_goods_activity_ids = [];
        if($intersect_act_ids)
        {
            $queryGoodsActivity = Activity::instance()
                ->whereIn('id',$intersect_act_ids)
                ->where('type',2)
                ->whereIn('status',[0,1])
                ->where('endtime','>=',$time_now)
                ->whereIn('sync_online',[0,2]);
            if( $is_vip['is_vip'] == 1 ) {
                $queryGoodsActivity->whereIn('target_type',[1,3,4]);
            }else{
                if($mid==0){
                    $queryGoodsActivity->where('target_type',1);
                }else{
                    $queryGoodsActivity->whereIn('target_type',[1,2,4]);
                }
            }
            $goods_activity = $queryGoodsActivity->get()->toArray();
            $goods_activity_map = array_column($goods_activity,null,'id');
            $goods_activity_group_data = getArrayGroupData($goods_activity,'rule_type');
            $has_goods_activity_ids = array_column($goods_activity,'id');

            //如果存在买赠
            if( isset($goods_activity_group_data[ActivityService::act_rule_type_send]) ) {
                $ids = array_column($goods_activity_group_data[ActivityService::act_rule_type_send],'id');
                $goods_activity_send_list = ActivitySendService::instance()->getActDataList($ids);
                $goods_activity_send_list_group = getArrayGroupData($goods_activity_send_list,'activity_id');
            }

            //如果存在直降
            if( isset($goods_activity_group_data[ActivityService::act_rule_type_drop]) ) {
                $ids = array_column($goods_activity_group_data[ActivityService::act_rule_type_drop],'id');
                $goods_activity_drop_list = ActivityDropService::instance()->getActDataList($ids);
                $goods_activity_drop_list_group = getArrayGroupData($goods_activity_drop_list,'activity_id');
            }

            //如果存在打折
            if( isset($goods_activity_group_data[ActivityService::act_rule_type_discount]) ) {
                $ids = array_column($goods_activity_group_data[ActivityService::act_rule_type_discount],'id');
                $goods_activity_discount_list = ActivityDiscountService::instance()->getActDataList($ids);
                $goods_activity_discount_list_group = getArrayGroupData($goods_activity_discount_list,'activity_id');
            }
        }

        //查询秒杀活动
        $query = Activity::instance()
            ->whereIn('id',$intersect_act_ids)
            ->where('cid',$cid)
            ->where('df',0)
            ->where('type',3)
            ->whereIn('status',[0,1])
            ->where('endtime','>=',$time_now)
            ->whereIn('sync_online',[0,2]);

        if( $is_vip['is_vip'] == 1 ) {
            $query->whereIn('target_type',[1,3,4]);
        }else{
            if($mid==0){
                $query->where('target_type',1);
            }else{
                $query->whereIn('target_type',[1,2,4]);
            }
        }

        $seckillActivity = $query->first();
        $seckillActivity = $seckillActivity ? $seckillActivity->toArray() : [];
        if( $seckillActivity )
        {
            //查询秒杀限购及商品
            $seckillRule = ActivitySeckill::instance()->info(['activity_id'=>$seckillActivity['id']]);
            $seckillGoods = ActivityGoods::instance()->where('activity_id')->whereIn('goods_id',$goods_ids)->get()->toArray();
            $seckillGoodsMap    = array_column($seckillGoods,null,'goods_id');
        }

        //查询拼团活动
        $query = Activity::instance()
            ->whereIn('id',$intersect_act_ids)
            ->where('cid',$cid)
            ->where('df',0)
            ->where('type',4)
            ->whereIn('status',[0,1])
            ->where('endtime','>=',$time_now)
            ->whereIn('sync_online',[0,2]);
        if( $is_vip['is_vip'] == 1 ) {
            $query->whereIn('target_type',[1,3,4]);

        }else{
            if($mid==0){
                $query->where('target_type',1);
            }else{
                $query->whereIn('target_type',[1,2,4]);
            }
        }

        $bookActivity = $query->first();
        $bookActivity = $bookActivity ? $bookActivity->toArray() : [];
        if($bookActivity) {
            $book_activity_id = $bookActivity['id'];
            $bookRule = ActivityBook::instance()->info(['activity_id'=>$book_activity_id]);
            if($bookRule) {
                $bookGoods = ActivityGoods::instance()
                    ->where('activity_id',$book_activity_id)
                    ->whereIn('goods_id',$goods_ids)
                    ->select()->toArray();
                $bookGoodsMap = array_column($bookGoods,null,'goods_id');
            }

            //0-不显示凑团，1-显示凑团
            if( $bookRule['show_book'] == 1 )
            {
                $teamList = BookTeam::instance()->select(explode(',','id,ld,people,new_people'))->where([
                    ['activity_id','=',$book_activity_id],
                    ['mn_sid','=',$mn_sid],
                    ['status','=',0],
                    ['goods_id','in',$goods_ids],
                    ['ld','>',$time]
                ])
                    ->selectRaw('new_people','< `people`')
                    ->get()->toArray();
                $teamListMap = array_column($teamList,null,'goods_id');
            }
        }
        //商品活动组装数据
        $new_goods_list = [];
        foreach ($baseGoodsList as $goods)
        {
            $goods_id   = $goods['id'];
            $listTag    = [];
            $detailTag  = [];
            $fullTag    = '';
            $goodsTag   = '';
            $sendActivity = 0;
            //----------------------店铺活动商品-------------------------------
            if( $fullActivity && $goods['pic_auth'] == 0 && ( $fullActivity['rule_type'] <>1 || ( $fullActivity['rule_type']==1 && !in_array($goods['is_bonded'],[1,2]) ) ) )
            {
                $content = '';
                $item['tagName'] = '整单促销';
                $rule_type      = $fullActivity['rule_type'];
                $activity_id    = $fullActivity['id'];

                switch ($rule_type)
                {
                    case ActivityService::act_rule_type_send://买赠
                        $sendList = $act_send_list_group[$activity_id];
                        foreach ($sendList as $send)
                        {
                            $unit       =  Activity::$unit[$send['unit_type']];
                            $content    .= '全场商品满'.round($send['full'],2).$unit.'赠'.round($send['send']).'件；';
                        }
                        $sendActivity = 1;
                        break;
                    case ActivityService::act_rule_type_drop://直降
                        $dropList = $act_drop_list_group[$activity_id];
                        foreach ($dropList as $drop )
                        {
                            $unit       = Activity::$unit[$drop['unit_type']];
                            $content    .= '满'.round($drop['full'],2).$unit.'减'.round($drop['drop'],2).'元；';
                        }
                        break;
                    case ActivityService::act_rule_type_discount://打折
                        $discountList = $act_discount_list_group[$activity_id];
                        foreach ($discountList as $disc)
                        {
                            $unit       = Activity::$unit[$disc['unit_type']];
                            $discount   = round($disc['discount']/10,1);
                            $content    .= '满'.round($disc['full'],2).$unit.'打'.$discount.'折；';
                        }
                        break;
                    default:
                        break;
                }

                $content = rtrim($content,'；');
                $item['tagDetail'] = $content;
                $fullTag=$content;
                $item['activity_id']= $activity_id;
                $fullActivity['notice'] = '';
                if($fullActivity['act_super']==0){
                    $fullActivity['notice']="整单促销和满减活动及限时特价活动不可叠加";
                }
                if($fullActivity['act_super']==1){
                    $fullActivity['notice']="整单促销和满减活动不可叠加";
                }
                if($fullActivity['act_super']==2){
                    $fullActivity['notice']="整单促销和限时特价活动不可叠加";
                }
                $detailTag[]=$item;
            }


            //--------------------------商品促销--------------------------------------
            $content    = '';
            $tag        = '';
            $goods_item = [];
            //当前商品的下的所有活动ID
            $goodsActivityList = $activityGoodsGroup[$goods_id] ??[];
            $goodsActivityIds  = array_column($goodsActivityList,'activity_id');

            //取出满足交集的第一个数据
            $intersect_goods_act_ids = array_intersect($goodsActivityIds, $has_goods_activity_ids);
            $current_act_id = current($intersect_goods_act_ids);
            $goodsActivity = $goods_activity_map[$current_act_id] ?? [];
            if($goodsActivity && $goods['pic_auth'] == 0 && ($goodsActivity['rule_type'] <>1 || ($goodsActivity['rule_type']==1 && !in_array($goods['is_bonded'],[1,2]))))
            {
                $rule_type      = $goodsActivity['rule_type'];
                $activity_id    = $goodsActivity['id'];

                switch ( $rule_type ){
                    case ActivityService::act_rule_type_send://买赠
                        $res = $goods_activity_send_list_group[$activity_id];
                        foreach ($res as $k=> $v)
                        {
                            $unit       =  ActivityService::instance()->unit[$v['unit_type']];
                            $content   .= '满'.round($v['full'],2).$unit.'赠'.round($v['send']).'件；';
                            if($k==0){
                                $tag="赠";
                            }
                        }

                        $content=rtrim($content,'；');
                        $goods_item['tagName']='满赠';
                        $sendActivity=1;
                        break;
                    case ActivityService::act_rule_type_drop://直降
                        $res= $goods_activity_drop_list_group[$activity_id];
                        foreach ($res as $k=>$v)
                        {
                            $unit    = ActivityService::instance()->unit[$v['unit_type']];
                            $content .= '满'.round($v['full'],2).$unit.'减'.round($v['drop'],2).'元；';
                            if($k==0){
                                if($v['unit_type']==0){
                                    $tag='满'.round($v['full'],2).'减'.round($v['drop'],2);
                                }else{
                                    $tag='满'.round($v['full'],2).$unit.'减'.round($v['drop'],2);
                                }
                            }
                        }
                        $content = rtrim($content,'；');
                        $goods_item['tagName']='满减';
                        break;
                    case ActivityService::act_rule_type_discount://打折
                        $res= $goods_activity_discount_list_group[$activity_id];
                        foreach ($res as $k=> $v)
                        {
                            $unit       = ActivityService::instance()->unit[$v['unit_type']];
                            $discount   = round($v['discount']/10,1);
                            $content   .= '满'.round($v['full'],2).$unit.'打'.$discount.'折；';
                            if($k==0){
                                if($v['unit_type']==0){
                                    $tag='满'.round($v['full'],2).'打'.$discount.'折';
                                }else{
                                    $tag='满'.round($v['full'],2).$unit.'打'.$discount.'折';
                                }
                            }
                        }
                        $content=rtrim($content,'；');
                        $goods_item['tagName']='满折';
                        break;
                    default:
                        break;
                }

                $goods_item['tagDetail']    = $content;
                $goodsTag                   = $content;
                $goods_item['activity_id']  = $goodsActivity['id'];
                $detailTag[]                = $goods_item;
                $listTag[]                  = $tag;
            }

            //---------------------------------秒杀活动-----------------------------------
            if(!empty($seckillActivity))
            {
                if( $time < $seckillActivity['begindate'] && $seckillActivity['begindate']-$time > 172800 )
                {
                    $seckillActivity = null;
                }
                else
                {
                    $time_start_str = strtotime($seckillActivity['begintime']);
                    $time_end_str   = strtotime($seckillActivity['endtime']);

                    if( $time > $seckillActivity['begindate'] && $time> $time_end_str && date('Y-m-d',$time) == date('Y-m-d',$seckillActivity['enddate']) )
                    {
                        $seckillActivity=$seckillActivityList[1]??null;
                        if( $seckillActivity && $seckillActivity['begindate']-$time<172800){
                            $seckillActivity=$this->checkActivityTime(['activity'=>$seckillActivity,'time'=>$time,'time_start_str'=>$time_start_str,'time_end_str'=>$time_end_str]);
                        }else{
                            $seckillActivity=null;
                        }
                    }else{
                        $seckillActivity=$this->checkActivityTime(['activity'=>$seckillActivity,'time'=>$time,'time_start_str'=>$time_start_str,'time_end_str'=>$time_end_str]);
                    }
                }

                if( isset($seckillGoodsMap[$goods_id]) )
                {
                    $seckillActivity['buy_limit']       = $seckillRule['buy_limit'];
                    $seckillActivity['buy_num']         = $seckillRule['buy_num'];
                    $seckillActivity['price_seckill']   = $seckillGoodsMap[$goods_id]['price'] ?? 0.00;
                }
            }
            //------------------------------------拼团活动-------------------------------------------------------------
            if(!empty($bookActivity))
            {
                if( $time < $bookActivity['begindate'] && $bookActivity['begindate']-$time>172800){
                    $bookActivity=null;
                }else{
                    $time_start_str=strtotime($bookActivity['begintime']);
                    $time_end_str=strtotime($bookActivity['endtime']);
                    if($time>$bookActivity['begindate'] && $time>$time_end_str && date('Y-m-d',$time)==date('Y-m-d',$bookActivity['enddate'])){
                        $bookActivity=$bookActivityList[1]??null;
                        if($bookActivity && $bookActivity['begindate']-$time<172800){
                            $bookActivity=$this->checkActivityTime(['activity'=>$bookActivity,'time'=>$time,'time_now_str'=>$time,'time_start_str'=>$time_start_str,'time_end_str'=>$time_end_str]);
                        }else{
                            $bookActivity=null;
                        }
                    }else{
                        $bookActivity=$this->checkActivityTime(['activity'=>$bookActivity,'time'=>$time,'time_now_str'=>$time,'time_start_str'=>$time_start_str,'time_end_str'=>$time_end_str]);
                    }
                }

                //当前商品存在拼团的情况
                if( isset($bookGoodsMap[$goods_id]) )
                {
                    $bookActivity['show']       = [];
                    $bookActivity['buy_limit']  = $bookRule['buy_limit'];
                    $bookActivity['buy_num']    = $bookRule['buy_num'];
                    $bookGoods                  = $bookGoodsMap[$goods_id];
                    $bookActivity['price']      = $bookGoods['price'];
                    if( $bookRule['show_book'] == 1 )
                    {
                        if( !empty($teamListMap[$goods_id]) )
                        {
                            $team = $teamListMap[$goods_id];
                            foreach ($team as $k=>$v)
                            {
                                $team[$k]['left_people']=$v['people']-$v['new_people'];
                                $team[$k]['countdown']=$v['ld']-$time;
                                $team[$k]['images']='';
                                $mid = Order::instance()->info(['is_sponsor'=>1,'book_id'=>$v['id'],'mn_sid'=>$mn_sid,'_fields_'=>'mid']);
                                if($mid){
                                    $team[$k]['images'] = MemberInfo::instance()->where('mid',$mid['mid'])->value('avatar');
                                }
                            }
                            $bookActivity['show']=$team;
                        }
                    }
                    $number=explode(',',$bookRule['num']);
                    $bookPriceStep=[];
                    $lowPrice=0;
                    foreach ($number as $k=>$v){
                        switch ($k){
                            case 0;
                            default:
                                $bookPriceStep[$v]=$bookGoods['price'];
                                if(($lowPrice>0 && $bookGoods['price']<$lowPrice) || $lowPrice==0){
                                    $lowPrice=$bookGoods['price'];
                                }
                                break;
                            case 1:
                                $bookPriceStep[$v]=$bookGoods['price_second'];
                                if(($lowPrice>0 && $bookGoods['price_second']<$lowPrice) || $lowPrice==0){
                                    $lowPrice=$bookGoods['price_second'];
                                }
                                break;
                            case 2:
                                $bookPriceStep[$v]=$bookGoods['price_third'];
                                if(($lowPrice>0 && $bookGoods['price_third']<$lowPrice) || $lowPrice==0){
                                    $lowPrice=$bookGoods['price_third'];
                                }
                                break;
                            case 3:
                                $bookPriceStep[$v]=$bookGoods['price_forth'];
                                if(($lowPrice>0 && $bookGoods['price_forth']<$lowPrice) || $lowPrice==0){
                                    $lowPrice=$bookGoods['price_forth'];
                                }
                                break;
                        }
                    }
                    $bookActivity['price_book']      = $lowPrice;
                    $bookActivity['price_book_step'] = $bookPriceStep;
                }
            }

            //组装最终活动数据
            $new_goods_list[] = [
                'goods_id'              => $goods_id,
                'fullActivity'          => empty($fullActivity)?null:$fullActivity,
                'fullActivityInfo'      => empty($fullActivityInfo)?null:$fullActivityInfo,
                'goodsActivity'         => empty($goodsActivity)?null:$goodsActivity,
                'seckillActivity'       => empty($seckillActivity)?null:$seckillActivity,
                'bookActivity'          => empty($bookActivity)?null:$bookActivity,
                'detailTag'             => empty($detailTag)?null:$detailTag,
                'listTag'               => empty($listTag)?null:$listTag,
                'goodsTag'              => $goodsTag,
                'fullTag'               => $fullTag,
                'sendActivity'          => $sendActivity
            ];
        }

        return $new_goods_list;
    }

    public function getTotalPrice($param)
    {
        ActivityService::instance()->updateActivityStatusDown();
        $activityInfo=Activity::instance()->info(['id'=>$param['activity_id']]);
        $total_price=$param['money'];
        $total_num=$param['num'];
        $drop_price=0;
        $send_num=0;
        $is_full=0;//是否满足活动需求
        $tag='';
        $send_goods=null;
        $dec='';
        $unite=$activityInfo['unit_type'];
        switch ($activityInfo['rule_type']){
            case 1://买赠
                $rule=ActivitySend::instance()->lists(['activity_id'=>$activityInfo['id'],'_order_'=>'full desc']);
                $num=count($rule);
                $goods_ids=[];
                $tag='满赠';
                foreach ($rule as $k=>$v){
                    if($unite==0){
                        if($total_price>=$v['full']){
                            $is_full=1;
                            $goods_ids=explode(',',$v['goods_ids']);
                            $send_num=$v['send'];
                            if($k==0){
                                $dec='已享满'.round($v['full'],2).'赠'.$v['send'].'件商品';
                                break;
                            }else{
                                $next=round($rule[$k-1]['full']-$total_price,2);
                                $dec='已享满'.round($v['full'],2).'赠'.$v['send'].'，再买'.$next.'元,可赠'.$rule[$k-1]['send'].'件商品';
                                break;
                            }
                        }
                    }else{
                        if($total_num>=$v['full']){
                            $is_full=1;
                            $goods_ids=explode(',',$v['goods_ids']);
                            $send_num=$v['send'];
                            if($k==0){
                                $dec='已享满'.round($v['full'],2).'件赠'.$v['send'].'件商品';
                                break;
                            }else{
                                $next=round($rule[$k-1]['full']-$total_num);
                                $dec='已享满'.round($v['full'],2).'件赠'.$v['send'].'，再买'.$next.'件,可赠'.$rule[$k-1]['send'].'件商品';
                                break;
                            }
                        }
                    }
                }
                if(empty($dec)){
                    if($unite==0){
                        $next=round($rule[$num-1]['full']-$total_price,2);
                        $dec='再买'.$next.'元,可赠'.$rule[$num-1]['send'].'件商品';
                    }else{
                        $next=round($rule[$num-1]['full']-$total_num,2);
                        $dec='再买'.$next.'件,可赠'.$rule[$num-1]['send'].'件商品';
                    }
                }
                if(!empty($goods_ids)){
                    foreach ($goods_ids as $v){
                        $goods=Goods::instance()->info(['id'=>$v,'_fields_'=>'id,name,img,is_trade,num_storage,status,is_bonded,df']);
                        $goods['is_select']=0;
                        $goods['select_num']=0;
                        if($goods['is_trade']==1){
                            $mnGoods=MnStoreGoods::instance()->info(['goods_id'=>$v,'mn_sid'=>$param['mn_sid']]);
                            if(!empty($mnGoods)  && $mnGoods['num']>0 && in_array($goods['is_bonded'],[0,3]) && $mnGoods['storestatus']==1){
                                $goods['num_storage']=$mnGoods['num'];
                                $has_batch = Goodsbatch::instance()->info(['goods_id' =>$v, 'df' => 0,'type'=>1,'mn_sid'=>$param['mn_sid'],'_order_'=>'cd asc']);
                                $goods['batch_id']=$has_batch['id']??0;
                                $send_goods[]=$goods;
                            }
                        }else{
                            if($goods['num_storage']>0 && in_array($goods['is_bonded'],[0,3]) && $goods['status']==1 && $goods['df']==0){
                                $has_batch = Goodsbatch::instance()->info(['goods_id' => $v, 'df' => 0,'type'=>0]);
                                $goods['batch_id']=$has_batch['id']??0;
                                $send_goods[]=$goods;
                            }
                        }
                    }
                }
                break;
            case 2://直降
                $rule=ActivityDrop::instance()->lists(['activity_id'=>$activityInfo['id'],'_order_'=>'full desc']);
                $num=count($rule);
                $tag='满减';
                foreach ($rule as $k=>$v){
                    if($unite==0){
                        if($total_price>=$v['full']){
                            $is_full=1;
                            $drop_price=$v['drop'];
                            if($k==0){
                                $dec='已享满'.round($v['full'],2).'减'.round($v['drop'],2);
                                break;
                            }else{
                                $next=round($rule[$k-1]['full']-$total_price,2);
                                $dec='已享满'.round($v['full'],2).'减'.round($v['drop'],2).'，再买'.$next.'元,可减'.round($rule[$k-1]['drop'],2);
                                break;
                            }
                        }
                    }else{
                        if($total_num>=$v['full']){
                            $is_full=1;
                            $drop_price=$v['drop'];
                            if($k==0){
                                $dec='已享满'.round($v['full'],2).'件减'.round($v['drop'],2);
                                break;
                            }else{
                                $next=round($rule[$k-1]['full']-$total_num,2);
                                $dec='已享满'.round($v['full'],2).'件减'.round($v['drop'],2).'，再买'.$next.'件,可减'.round($rule[$k-1]['drop'],2);
                                break;
                            }
                        }
                    }
                }
                if(empty($dec)){
                    if($unite==0){
                        $next=bcsub((string)$rule[$num-1]['full'],(string)$total_price,2);
                        $dec='再买'.$next.'元,可减'.round($rule[$num-1]['drop'],2);
                    }else{
                        $next=bcsub((string)$rule[$num-1]['full'],(string)$total_num,2);
                        $dec='再买'.$next.'件,可减'.round($rule[$num-1]['drop'],2);
                    }
                }
                break;
            case 3://打折
                $rule=ActivityDiscount::instance()->lists(['activity_id'=>$activityInfo['id'],'_order_'=>'full desc']);
                $num=count($rule);
                $tag='满折';
                foreach ($rule as $k=>$v){
                    $discount=round($v['discount']/10,1);
                    if($unite==0){
                        if($total_price>=$v['full']){
                            $is_full=1;
                            $drop_price=round($total_price*(100-$v['discount'])/100,2);
                            if($k==0){
                                $dec='已享满'.round($v['full'],2).'打'.$discount.'折';
                                break;
                            }else{
                                $next=round($rule[$k-1]['full']-$total_price,2);
                                $next_discount=round($rule[$k-1]['discount']/10,1);
                                $dec='已享满'.round($v['full'],2).'打'.$discount.'折，再买'.$next.'元,可打'.$next_discount.'折';
                                break;
                            }
                        }
                    }else{
                        if($total_num>=$v['full']){
                            $is_full=1;
                            $drop_price=round($total_price*(100-$v['discount'])/100,2);
                            if($k==0){
                                $dec='已享满'.round($v['full'],2).'件打'.$discount.'折';
                                break;
                            }else{
                                $next=round($rule[$k-1]['full']-$total_num,2);
                                $next_discount=round($rule[$k-1]['discount']/10,1);
                                $dec='已享满'.round($v['full'],2).'件打'.$discount.'折，再买'.$next.'件,可打'.$next_discount.'折';
                                break;
                            }
                        }
                    }
                }
                if(empty($dec)){
                    $next_discount=round($rule[$num-1]['discount']/10,1);
                    if($unite==0){
                        $next=round($rule[$num-1]['full']-$total_price,2);
                        $dec='再买'.$next.'元,可打'.$next_discount.'折';
                    }else{
                        $next=round($rule[$num-1]['full']-$total_num,2);
                        $dec='再买'.$next.'件,可打'.$next_discount.'折';
                    }
                }
                break;
        }
        return [
            'status'=>Normal::SUC,
            'msg'=>'请求成功',
            'data'=>[
                'total_price'=>$total_price,
                'dec'=>$dec,
                'tag'=>$tag,
                'drop_price'=>$drop_price,
                'send_goods'=>$send_goods,
                'send_num'=>$send_num,
                'is_full'=>$is_full
            ]
        ];
    }
}